package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.CategoryAttributeTemplateMapper;
import cn.tedu.csmall.product.mapper.CategoryMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.dto.CategoryAddNewDTO;
import cn.tedu.csmall.product.pojo.dto.CategoryDTO;
import cn.tedu.csmall.product.pojo.dto.CategoryUpdateDTO;
import cn.tedu.csmall.product.pojo.entity.Category;
import cn.tedu.csmall.product.pojo.vo.AlbumStandardVO;
import cn.tedu.csmall.product.pojo.vo.CategoryListItemVO;
import cn.tedu.csmall.product.pojo.vo.CategoryStandardVO;
import cn.tedu.csmall.product.service.ICategoryService;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.List;

@Slf4j
@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandCategoryMapper brandCategoryMapper;

    @Autowired
    private CategoryAttributeTemplateMapper categoryAttributeTemplateMapper;

    @Autowired
    private SpuMapper spuMapper;

    public CategoryServiceImpl(){
        log.debug("创建业务对象:CategoryServiceImpl");
    }


    @Transactional
    public void addNew(CategoryAddNewDTO categoryAddNewDTO){
        log.debug("开始处理【添加类别】的业务，参数：{}", categoryAddNewDTO);

        // 查询父级类别
        Integer depth = 1;
        Long parentId = categoryAddNewDTO.getParentId();
        CategoryStandardVO parentCategory = null;
        if (parentId != 0) {
            // 确定当前类别的depth值，为：父级depth + 1
            parentCategory = categoryMapper.getStandardById(parentId);
            log.debug("根据父级类别ID【{}】查询父级类别详情，结果：{}", parentId, parentCategory);
            if (parentCategory == null) {
                String message = "添加类别失败，所选择的父级类别不存在！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
            }
            depth = parentCategory.getDepth() + 1;
        }
        log.debug("当前尝试添加的类型的depth值为：{}", depth);

        // 调用Mapper对象的【根据名称统计数量】方法进行统计
        String name = categoryAddNewDTO.getName();
        int count = categoryMapper.countByName(name);
        log.debug("根据名称【{}】统计数量：{}", name, count);
        // 判断统计结果是否大于0
        if (count > 0) {
            // 是：名称已经被占用，抛出异常（CONFLICT）
            String message = "添加类别失败，尝试添加的类别名称【" + name + "】已经存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 创建Category实体类的对象
        Category category = new Category();
        // 将参数DTO的各属性值复制到Category实体类对象中
        BeanUtils.copyProperties(categoryAddNewDTO, category);
        // 补全Category对象的值：depth >>> 使用以上的depth变量
        category.setDepth(depth);
        // 补全Category对象的值：isParent >>> 0，新增的类别的isParent固定为0
        category.setIsParent(0);
        // 调用Mapper对象的方法，将数据插入到数据库，并获取返回值
        log.debug("准备向数据库中写入类别数据：{}", category);
        int rows = categoryMapper.insert(category);
        if (rows != 1 ){
            String message = "添加类别失败,服务器忙稍后再试";
            log.debug(message);
            throw  new ServiceException(ServiceCode.ERR_INSERT,message);
        }

        // 检查当前新增类型的父级类别，如果父类别的isParent为0，则将父级类别的isParent更新为1
        if (parentId != 0) {
            if (parentCategory.getIsParent() == 0) {
                Category updateParentCategory = new Category();
                updateParentCategory.setId(parentId);
                updateParentCategory.setIsParent(1);
                log.debug("将父级类别的isParent更新为1，更新的参数对象：{}", updateParentCategory);
                int row = categoryMapper.update(updateParentCategory);
                if (row != 1 ){
                    String message = "添加类别失败,服务器忙稍后再试";
                    log.debug(message);
                    throw  new ServiceException(ServiceCode.ERR_UPDATE,message);
                }
            }
        }
    }

    @Override
    public void setEnable(Long id){
        updateEnableById(id,1);
    }

    @Override
    public void setDisable(Long id){
        updateEnableById(id,0);
    }

    public void updateEnableById(Long id,Integer enable){
        String[] s = {"禁用","启用"};
        log.debug("处理"+s[enable]+"类别请求");
        //判断id是否为1
        if (id == 1){
            String message = s[enable]+"类别失败了,因为他是神";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        CategoryStandardVO standardById = categoryMapper.getStandardById(id);
        if (standardById==null){
            String message = s[enable]+"类别失败了,没有这个id";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        if (standardById.getEnable()==enable){
            String message = s[enable]+"类别失败了,enable一样";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        Category category = new Category();
        category.setId(id);
        category.setEnable(enable);
        int rows = categoryMapper.update(category);

        if (rows!=1){
            String message = s[enable]+"类别失败了,服务已繁忙";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
    }

    @Override
    public List<CategoryListItemVO> list(){
        log.debug("开始处理查看类别列表服务");
        List<CategoryListItemVO> list = categoryMapper.list();
        return list;

    }

    @Override
    public void setDisplay(Long id){
        updateDisplayById(id,1);
    }

    @Override
    public void setHidden(Long id){
        updateDisplayById(id,0);
    }

    public void updateDisplayById(Long id,Integer display){
        String[] s = {"未启用","启用"};
        //判断id是否为1
        if (id == 1){
            String message = "处理类别"+s[display]+"失败,以为他是1号";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        //判断该id存在的数据是否存在
        CategoryStandardVO standardById = categoryMapper.getStandardById(id);
        if (standardById==null){
            String message = "处理类别"+s[display]+"失败,没有这个id";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        if (standardById.getIsDisplay()==display){
            String message = "处理类别"+s[display]+"失败,这个id已经"+s[display];
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        Category category = new Category();
        category.setId(id);
        category.setIsDisplay(display);
        int update = categoryMapper.update(category);
        if (update!=1){
            String message = "处理类别"+s[display]+"失败,服务器繁忙";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

    }

    @Override
    public CategoryStandardVO selectById(Long id){
        log.debug("开始处理根据id查看详情的服务");
        CategoryStandardVO standardById = categoryMapper.getStandardById(id);
        if (standardById == null){
            String message = "别瞎查,没有这个id";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return standardById;
    }

    @Override
    public void update(CategoryUpdateDTO categoryUpdateDTO){
        log.debug("开始修改详情");

        String name = categoryUpdateDTO.getName();
        int rows = categoryMapper.countByName(name);
        if (rows >= 1){
            String message = "修改失败,名字已存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdateDTO,category);
        rows = categoryMapper.update(category);
        if (rows != 1){
            String message = "修改失败,服务器繁忙";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
    }

    @Override
    public void delete(Long id){
        log.debug("开始处理根据id删除类别的业务");
        CategoryStandardVO standardById = categoryMapper.getStandardById(id);
        if (standardById == null){
            String message = "删除失败,这个类不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        int rows = brandCategoryMapper.countByCategory(id);
        if (rows >= 1){
            String message = "删除失败,这个id与品牌与类别关联";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        rows = categoryAttributeTemplateMapper.countByCategory(id);
        if (rows >= 1){
            String message = "删除失败,这个id与类别与属性模版关联";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        rows = spuMapper.countByCategory(id);
        if (rows >= 1){
            String message = "删除失败,这个id与SPU关联";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        rows = categoryMapper.deleteById(id);
        if (rows!=1){
            String message = "删除失败,服务器繁忙";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
        /**判断是不是最后一个*/
        Long parentID = standardById.getParentId();
        rows = categoryMapper.countByParentId(parentID);
        if (rows == 0){
            Category category = new Category();
            id = standardById.getParentId();
            category.setId(id);
            category.setIsParent(0);
            categoryMapper.update(category);
        }

    }

    @Override
    public List<CategoryListItemVO> listByParentId(Long parentId) {
        log.debug("开始处理【查询类别列表】的业务，无参数");
        return categoryMapper.listByParentId(parentId);
    }

}
